<template>
  <div class="content">
    <nut-navbar class="navbar" z-index="5" :clickable="false" fixed safe-area-inset-top>
      <template #content>
        <span>{{ t(String(route.meta.title)) }}</span>
      </template>
      <template #left>
        <img src="/imgs/club/arrow_left.png" alt="" @click="router.go(-1)" class="arrow_left" />
      </template>
      <template #right>
        <span class="save" @click="goToApprovalMenber">
          {{ t('club_page_cysp') }} <span v-if="clubOtherInfo.approve_count > 0" class="unread_badge">{{
            clubOtherInfo.approve_count }}</span>
        </span>
      </template>
    </nut-navbar>

    <!-- 搜索 -->
    <div class="search_box">
      <nut-searchbar class="search_input" :max-length="30" :placeholder="t('club_page_searchid')" v-model="searchVal"
        @change="onClickSearch" shape="square" background="transparent" input-background="#1D1C3C">
        <template #leftin>
          <iconpark-icon name="sousuo" size="14" />
        </template>
      </nut-searchbar>
      <span class="search_btn" @click="getSearchClubMember">{{ t('club_page_ss') }}</span>
    </div>

    <!-- 成员 -->
    <div class="con_list" :style="contentStyle()">
      <nut-infinite-loading v-model="infinityValue" load-more-txt=" " :has-more="hasMore" @load-more="onLoad">
        <nut-empty v-if="members.length == 0" :description="t('nomore_data')"></nut-empty>
        <div class="member_container" v-else>
          <div v-for="(member) in members" :key="member.role_id" class="member_item">
            <div class="member_info">
              <img :src="typeof member.head_photo === 'number' || !isNaN(Number(member.head_photo))
                ? `/imgs/head_icons/${member.head_photo}.webp`
                : joinURL(settings.media_url, member.head_photo)" alt="" class="member_avatar" />
              <div class="info">
                <div class="name_section">
                  <p class="member_name">{{ member.username }}</p>
                  <span v-if="member.is_admin === 1 || member.is_club_creator === 1" class="tag" :class="{
                    creator: member.is_club_creator === 1 ? 'creator' : '',
                    admin: (member.is_admin === 1 && member.is_club_creator === 0) ? 'admin' : '',
                  }">
                    <em class="tag_text">{{ member.is_club_creator === 1 ? t('club_page_cjz') : (member.is_admin === 1 ?
                      t('club_page_admin') : '') }}</em>
                  </span>
                </div>
                <span class="vip_tag" :class="'vip_' + member.level">
                  <ImgT :key="member.level" :src="`/imgs/vip/vipIcon/vip_${member.level}.webp`" alt="" />
                </span>
              </div>
            </div>
            <div class="member_actions" v-if="roleClubId == clubId">
              <!-- 俱乐部创建者可以设置/取消管理员 -->
              <span v-if="member.is_club_creator === 0" class="action_btn" @click="updateRole(member, 'update')">
                {{ member.is_admin === 1 ? t('club_page_qxadmin') : t('club_page_szadmin') }}
              </span>
              <!-- 俱乐部创建者可以踢出普通成员和管理员 -->
              <span v-if="member.is_club_creator === 0" class="action_btn" @click="removeMember(member, 'del')">
                {{ t('club_page_tc') }}
              </span>
            </div>
            <!-- **管理员视角：只能踢出普通成员** -->
            <div class="member_actions" v-if="roleClubId != clubId">
              <span v-if="member.is_club_creator === 0 && member.is_admin === 0" class="action_btn"
                @click="removeMember(member, 'del')">
                {{ t('club_page_tc') }}
              </span>
            </div>

          </div>
        </div>
      </nut-infinite-loading>
    </div>


    <Modal v-model:visible="isShowWin" :title="t(club_title)" @close="">
      <div class="popup_body">
        <div class="info">{{ club_tip }}</div>
        <div class="submit_btn">
          <span class="submit_close" @click="close">{{ t('cancel') }}</span>
          <Btn height="44px" width="147px" class="submit" v-if="isDel === 'del'" @click="submitAc(0)">{{ t('confirm') }}
          </Btn>
          <Btn height="44px" width="147px" class="submit" v-else @click="submitAc(1)">{{ t('confirm') }}</Btn>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { useI18n } from "vue-i18n";
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import pinia from '@/store/index';
import { storeToRefs } from 'pinia';
import { Page } from '@/store/page';
import { joinURL } from '@/utils/publicMethods'

import PKwebsocket from "@/lolo/Ws";
import { NetPacket } from "@/netBase/NetPacket";

import { showToast } from "@nutui/nutui";

const {
  settings,
} = storeToRefs(Page(pinia));
import { User } from "@/store/user";
import { Local } from "@/utils/storage";
const { appHeight } = storeToRefs(User(pinia));

const route = useRoute();
const router = useRouter();
const { t } = useI18n();

const infinityValue = ref(false);
const hasMore = ref(true);
const searchVal = ref('')
const searchValFalg = ref(false)


// 成员列表
const members = ref<any>([]);

const isShowWin = ref(false);
const club_title = ref('');
const club_tip = ref('')
const clubId = ref<any>(null)
const isAdmin = ref(0)
const roleId = ref();
const isDel = ref('del');
const clubOtherInfo: any = ref({})
const roleClubId = ref(0)

const params: any = reactive({
  // 参数
  pageSize: 10,
  page: 1,
});

const goToApprovalMenber = () => {
  router.push({
    path: "/club/member/approvalMenber",
    query: {
      club_id: clubId.value,
    },
  });
}


// const isShowApply = ref(false);
// const apply_title = ref('');

// const goToPage = () => {
//   isShowApply.value = true
//   apply_title.value = '提示'
// }

// const closeApply = () => {
//   isShowApply.value = false
// }

// const submitAp = () => {
//   getAdminApplication()
//   isShowApply.value = false
// }

// // 申请俱乐部管理员
// const getAdminApplication = () => {
//   const req = NetPacket.req_admin_application();
//   req.club_id = clubId.value
//   H5Websocket.sendMessageHandler(req);
//   MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_admin_application, getAdminApplicationHandle);
// };
// // 申请俱乐部管理员返回
// const getAdminApplicationHandle = (res: any) => {
//   const tipStr: any = {
//     0: '操作成功',
//     1: '俱乐部不存在',
//     2: '已经是俱乐部管理员',
//     3: '管理员申请在审核中',
//     4: '不能申请自己创建的俱乐部的管理员',
//     5: '不是俱乐部成员',
//   };
//   if (res.result === 0) {
//     showToast.text(t(tipStr[res.result]))
//     // getClubMember()
//   } else {
//     showToast.text(t(tipStr[res.result]))
//   }
//   MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_admin_application, null);
// };

// 搜索
const onClickSearch = () => {
  if (searchVal.value) {
    if (/^\d+$/.test(searchVal.value)) {
      searchValFalg.value = true
    } else {
      searchValFalg.value = false
    }
  }
}
const contentStyle = () => {
  return window.matchMedia("(display-mode: standalone)").matches ||
    window.navigator.standalone
    ? { height: `calc(${appHeight.value}px - 200px)` }
    : { height: `calc(${appHeight.value}px - 200px)` };
};


// 获取俱乐部其它信息
const getClubOtherInfo = () => {
  const req = NetPacket.req_get_extra_club_info();
  req.club_id = clubId.value
  PKwebsocket.instance.send(req, true, {
    callbackName: "msg_notify_get_extra_club_info",
    callback: getClubOtherInfoHandle,
  });
};
// 俱乐部信息其它返回
const getClubOtherInfoHandle = (res: any) => {
  console.log('俱乐部其它信息', res)
  clubOtherInfo.value = res
};

const getSearchClubMember = () => {
  params.page = 1;
  members.value = []
  infinityValue.value = false;
  hasMore.value = true;
  getClubMember()
}

// 获取成员列表
const getClubMember = () => {
  infinityValue.value = true;
  const req = NetPacket.req_club_member();
  req.club_id = clubId.value
  req.username = searchValFalg.value ? '' : searchVal.value
  req.role_id = searchValFalg.value ? Number(searchVal.value) : 0
  req.page = params.page
  req.page_size = params.pageSize;
  PKwebsocket.instance.send(req, true, {
    callbackName: "msg_notify_club_member",
    callback: getClubMemberHandle,
  });
};
// 成员列表返回
const getClubMemberHandle = (res: any) => {
  if (res.info.length < params.pageSize) {
    hasMore.value = false;
  } else {
    hasMore.value = true;
  }
  members.value = [...members.value, ...res.info];
  infinityValue.value = false;
};

const onLoad = () => {
  if (hasMore.value) {
    params.page++;
    getClubMember();
  } else {
    console.log('没有更多数据了');
  }
};

//设置管理
const addAdmin = (roleId: any) => {
  const req = NetPacket.req_add_admin();
  req.club_id = clubId.value;
  req.role_id = roleId;
  PKwebsocket.instance.send(req, true, {
    callbackName: "msg_notify_add_admin",
    callback: addAdminHandle,
  });
}
const addAdminHandle = (res: any) => {
  const tipStr: any = {
    0: t('club_page_szcg'),
    1: t('club_page_bsjlbhy'),
    2: t('club_page_ysadmin'),
    3: t('club_page_adminsx'),
    4: t('club_page_fcjzjlb')
  };
  if (res.result === 0) {
    showToast.text(t(tipStr[res.result]))
    setTimeout(() => {
      getSearchClubMember()
    }, 1000)
  } else {
    showToast.text(t(tipStr[res.result]))
  }
}

//取消管理
const delAdmin = (roleId: any) => {
  const req = NetPacket.req_del_admin();
  req.club_id = clubId.value;
  req.role_id = roleId;
  PKwebsocket.instance.send(req, true, {
    callbackName: "msg_notify_del_admin",
    callback: addDelHandle,
  });
}
const addDelHandle = (res: any) => {
  const tipStr: any = {
    0: t('club_page_qxcg'),
    1: t('club_page_bsjlbhy'),
    2: t('club_page_wjbsadmin'),
    3: t('club_page_bsjlbcjz'),
  };
  if (res.result === 0) {
    showToast.text(t(tipStr[res.result]))
    setTimeout(() => {
      getSearchClubMember()
    }, 1000)
  } else {
    showToast.text(t(tipStr[res.result]))
  }
}

//踢出成员
const clubKickout = (roleId: number) => {
  const req = NetPacket.req_club_kickout();
  req.club_id = Number(clubId.value)
  req.role_id = roleId
  PKwebsocket.instance.send(req, true, {
    callbackName: "msg_notify_club_operate",
    callback: clubKickoutHandle,
  });
}
const clubKickoutHandle = (res: any) => {
  const tipStr: any = {
    0: t('club_page_tccg'),
    1: t('bank_tip_fail'),
  };
  if (res.rlt === 0) {
    showToast.text(t(tipStr[res.rlt]))
    setTimeout(() => {
      getSearchClubMember()
    }, 1000)
  } else {
    showToast.text(t(tipStr[res.rlt]))
  }
}

// 更新角色
const updateRole = (member: any, del: string) => {
  club_tip.value = member.is_admin == 0 ? t('club_page_szwgly', { username: member.username }) : t('club_page_qxwgly', { username: member.username });
  isAdmin.value = member.is_admin;
  roleId.value = member.role_id;
  isDel.value = del
  isShowWin.value = true;
};

// 移除成员
const removeMember = (member: any, del: string) => {
  isDel.value = del
  club_tip.value = t('club_page_tcjlb', { username: member.username });
  roleId.value = member.role_id
  isShowWin.value = true;
};

const submitAc = (type: number) => {
  if (type === 1) {
    if (isAdmin.value == 1) {
      delAdmin(roleId.value)
    } else {
      addAdmin(roleId.value)
    }
  } else {
    clubKickout(roleId.value)
  }
  isShowWin.value = false
};

const close = () => {
  isShowWin.value = false
};

onMounted(async () => {
  const { club_id } = route.query;
  clubId.value = String(club_id)
  roleClubId.value = Local.get('clubId')
  await getClubOtherInfo()
  await getClubMember()
});

onUnmounted(() => {

});
</script>

<style scoped lang="scss">
.content {
  font-size: 14px;
  margin: 0 0 10px;

  .arrow_left {
    width: 24px;
    height: 24px;
  }

  .save {
    height: 32px;
    line-height: 32px;
    text-align: center;
    color: #5BD9FF;
    position: relative;

    .unread_badge {
      width: 16px;
      height: 16px;
      text-align: center;
      line-height: 16px;
      background: #ff5050;
      color: #fff;
      border-radius: 50%;
      font-size: 10px;
      position: absolute;
      top: -4px;
      right: -12px;
      z-index: 9;
    }

  }

  .search_box {
    // width: 347px;
    margin: 20px auto 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .search_input {

    :deep(.square) {
      border-radius: 8px;
      height: 44px;
      box-shadow: 0.5px 0.5px 1px 0px #2E296B inset;
    }
  }

  .search_btn {
    width: 82px;
    height: 44px;
    margin-right: 14px;
    font-size: 14px;
    line-height: 44px;
    text-align: center;
    color: #FFFFFF;
    background: linear-gradient(180deg, #5567FF 0%, #9E1EFF 100%);
    box-shadow: 0.5px 0.5px 1px 0px #9B9EFF inset;
    border-radius: 8px;
  }

  .con_list {
    overflow: auto;
  }

  .member_container {
    // padding: 20px;
    width: 347px;
    margin: 0 auto;

    .member_item {
      height: 62px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: #131232;
      box-shadow: 0.5px 0.5px 1px 0px #2E296B inset;
      border-radius: 10px;
      padding: 10px 15px;
      margin-bottom: 10px;
      position: relative;

      .member_info {
        display: flex;
        align-items: center;


        .member_avatar {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          margin-right: 10px;
        }

        .info {
          display: flex;
          flex-direction: column;

          .name_section {
            display: flex;
            align-items: center;
            gap: 8px;


            .member_name {
              font-size: 14px;
              font-weight: bold;
              margin: 0;
              color: #FFFFFF;
            }

            .tag {
              width: 41px;
              height: 36px;
              line-height: 26px;
              font-size: 10px;
              border-radius: 6px;
              color: #fff;
              position: absolute;
              left: 0;
              top: 0;
              z-index: 99;

              .tag_text {
                display: inline-block;
                transform: rotate(-40deg);
              }
            }

            .creator {
              background: url(/imgs/club/cjz.webp) no-repeat;
              background-size: 100% 100%;
            }

            .admin {
              background: url(/imgs/club/gly.webp) no-repeat;
              background-size: 100% 100%;
            }
          }

          .vip_tag {
            margin-top: 5px;

            img {
              width: 50px;
              height: 20px;
            }
          }
        }
      }

      .member_actions {
        display: flex;
        gap: 10px;

        .action_btn {
          height: 32px;
          line-height: 32px;
          font-size: 12px;
          text-align: center;
          color: #C6C4F5;
          padding: 0 8px;
          background: #282747;
          box-shadow: 0.5px 0.5px 1px 0px #C6C4F5 inset;
          border-radius: 8px;
        }
      }
    }
  }


}

.popup_body {
  color: #fff;
  padding: 10px;

  .info {
    margin-bottom: 10px;
    text-align: center;
    color: #FFFFFF;
    margin: 24px 0;
  }

  .submit_btn {
    margin: 20px 0;
    display: flex;
    justify-content: space-evenly;

    .submit_close {
      width: 147px;
      height: 42px;
      color: #FFFFFF;
      text-align: center;
      line-height: 44px;
      background: #282747;
      box-shadow: 0.5px 0.5px 1px 0px #2E296B inset;
      border-radius: 8px;
    }
  }
}
</style>
